local cjson = require("cjson")

local ngx_req = ngx.req
local ngx_log = ngx.log
local ngx_print = ngx.print
local ngx_exit = ngx.exit

local function _verify_request_params(params)
  if params.method ~= "GET" then
    return nil, "register not support " .. params.method .. " method"
  end
  if not params.key then
    return nil, "missing key"
  end
  return true
end

local args = ngx_req.get_uri_args()

local params = {
  method = ngx_req.get_method(),
  key = args.key,
}

local ok, err = _verify_request_params(params)

if not ok then
  ngx_log(ngx.ERR, "failed to verify server: ", err)
  ngx_print(cjson.encode({ errmsg = "failed to verify request: " .. err }))
  return ngx_exit(ngx.HTTP_OK)
end

ngx.header["Content-Type"] = "application/json;charset=UTF-8"

local red = require("resty.wechat.utils.redis"):connect(wechat_config.redis).redis

local key_exist = red:sismember("app_set", params.key)

if key_exist and key_exist == 0 then
  ngx_print(cjson.encode({ errmsg = "app_key:[" .. params.key .. "] is not registered!" }))
  return ngx_exit(ngx.HTTP_OK)
end

red:srem("app_set", params.key)
red:del("app_data:" .. params.key)
red:del("access_token:" .. params.key)
red:del("ticket:" .. params.key)

ngx_print(cjson.encode({ errmsg = "sucess deregister app : " .. params.key }))
return ngx_exit(ngx.HTTP_OK)
